<?php exit;

//成功更新文章后:
if ($isfirst) {
    $firstimg = param_null('firstimg');
    $source = param_null('source');
    $sourceurl = param_null('sourceurl');
    $expired = param_null('expired');
    if ($expired === '') $expired = 0;
    if (!empty($expired) && !is_numeric($expired)) {
        $expired = strtotime($expired);
    }

    if ($TitleImgEnable && $firstimg !== NULL) {
        $firstimg_tmp = pickup_title_pic($tid, $firstimg, (isset($GLOBALS['attach_imgs']) ? $attach_imgs : null));
        if (!empty($firstimg_tmp)) {
            $firstimg = $firstimg_tmp;
            unset($firstimg_tmp);
        }
    }
    if (isset($GLOBALS['attach_imgs'])) unset($GLOBALS['attach_imgs']);//清除临时变量

    $updcols = array();
    $condext = array('tid' => $tid);
    if ($expired !== NULL) $updcols['expired'] = $expired;
    if ($source !== NULL) $updcols['source'] = $source;
    if ($sourceurl !== NULL) $updcols['sourceurl'] = $sourceurl;
    if ($TitleImgEnable) {
        if ($firstimg !== NULL) $updcols['firstimg'] = $firstimg;
    }
    $to_chg_kw_fid = ($fid != $newfid);
    if ($IsThreadExtension) {
        $keywords = param_null('keywords');
        $metadesc = param_null('metadesc');
        $relatedlinks = param_null('relatedlinks');
        $relatedfids = param_null('relatedfids');
        $editornote = param_null('editornote');
        $reviseerr = param_null('reviseerr');
        $aflags = param_null('aflags');
        if ($aflags === '') $aflags = 0;
        $viwetemplate = param_null('viwetemplate');

        if ($keywords !== NULL) $updcols['keywords'] = $keywords;
        if ($metadesc !== NULL) $updcols['metadesc'] = $metadesc;
        if ($relatedlinks !== NULL) $updcols['relatedlinks'] = $relatedlinks;
        if ($relatedfids !== NULL) $updcols['relatedfids'] = $relatedfids;
        if ($editornote !== NULL) $updcols['editornote'] = $editornote;
        if ($reviseerr !== NULL) $updcols['reviseerr'] = $reviseerr;
        if ($aflags !== NULL) $updcols['aflags'] = $aflags;
        if($IsAdjustViewTemplate && $viwetemplate !== NULL){
            $updcols['viwetemplate'] = $viwetemplate;
        }
    }
    if (!empty($updcols)) {
        $Label_extended_fields = array('distclass' => $newfid);
        if (isset($updcols['keywords']) || isset($updcols['relatedlinks'])) $updcols['relatedupdtime'] = time();
		if(!isset($threadext_data) || empty($threadext_data) || !isset($threadext_data['relatedlinks']))
			$dbopt = db_find_one($theadext_table, $condext, array(), array('tid', 'keywords', 'relatedlinks','relatedfids'));
		else
			$dbopt = &$threadext_data;//前面已经查询,不必重复
        $keywordLs = StrToLabel($keywords, 'thread', true);
        if ($keywords !== null || $relatedlinks !== null) {
            if(!empty($keywordLs)){
                $keywords_i = implode(',',array_keys($keywordLs));
                if($keywords_i != $keywords)
                    $updcols['keywords'] = $keywords = $keywords_i;
                unset($keywords_i);
            }
            $base_relatedlink_only = $upd_relatedlink_manually = false;
            if($relatedfids === NULL) $relatedfids = $dbopt['relatedfids'];
            if (empty($keywords) && !empty($dbopt) && !empty($dbopt['relatedlinks'])) {//清空:
                $relatedlinks_txt = ($relatedlinks === NULL ? $dbopt['relatedlinks'] : $relatedlinks);
                $relatedlinkrules =  &ParseRelatedLinkExclude($relatedlinks_txt);
                if (!empty($relatedlinkrules)) {
                    $relatedsp = array();
                    $delautogls = 0;
                    foreach ($relatedlinkrules as &$relatedlinkrule) {
                        if (isset($relatedlinkrule['mark']) && !empty($relatedlinkrule['mark'])) {
                            $relatedsp[] = &$relatedlinkrule['RawLine'];
                        } else
                            $delautogls++;
                    }
                    $upd_relatedlink_manually = ($keywords === NULL and !empty($relatedlinks) and $delautogls > 0);//手动更新relatedlink
                    if (!$upd_relatedlink_manually)
                        $relatedlinks = $updcols['relatedlinks'] = implode(PHP_EOL, $relatedsp).PHP_EOL;
                    else {
                        $relatedlinks = '';
                        foreach ($relatedlinkrules as &$relatedlinkrule) {
                            $relatedlinks .= $relatedlinkrule['RawLine'] . PHP_EOL;
                        }
                        $updcols['relatedlinks'] = $relatedlinks;
                        unset($relatedlinkrule);
                    }
                    unset($relatedsp);
                    $base_relatedlink_only = true;
                }
            }
            $clear_relatedlink = ($keywords === NULL and $relatedlinks !== NULL and empty(trim($relatedlinks)));
            if ((!$base_relatedlink_only && !empty($keywordLs) && !$upd_relatedlink_manually) || $clear_relatedlink) {
                $relatedlinkrules = $ExcludeDistRows = null;
                $must_include_links = array();
                $must_includes = 0;
                $ExcludeDistRows = array(array('table' => 'thread', 'id' => $tid));//先排除自身
                $relatedlinks_txt = ($relatedlinks === NULL ? $dbopt['relatedlinks'] : $relatedlinks);
                if (!empty($relatedlinks_txt)) {
                    $relatedlinkrules =  &ParseRelatedLinkExclude($relatedlinks_txt);
                    $edrs = array();
                    if (!empty($relatedlinkrules)) {
                        $add_old_relatedlinkrules = false;
                        if ($relatedlinks === NULL && $relatedfids != '-1') {//注意不关联的选项
                            $relatedlinks = '';
                            $add_old_relatedlinkrules = true;
                        }
                        foreach ($relatedlinkrules as &$relatedlinkrule) {
                            if (isset($relatedlinkrule['mark']) && !empty($relatedlinkrule['mark'])) {
                                if ($relatedlinkrule['mark'] == '!' || $relatedlinkrule['mark'] == '-')
                                    $edrs[] = &$relatedlinkrule;
                                elseif ($relatedlinkrule['mark'] == '+' || $relatedlinkrule['mark'] == '*') {
                                    $must_includes++;
                                    $must_include_links[] = &$relatedlinkrule;
                                }
                                if ($add_old_relatedlinkrules) {
                                    $relatedlinks .= $relatedlinkrule['RawLine'] . PHP_EOL;
                                }
                            }
                        }
                    }
                    if (!empty($edrs)) $ExcludeDistRows = array_merge($ExcludeDistRows, $edrs);
                }
                if ($must_includes < 10 && $relatedfids != '-1') {
                    $search_lg_conditions = array('disabled' => 0, 'fid' => $relatedfids);
                    if ($keywords === NULL) {//重新生成关联链接的操作:
                        $keywordLs = StrToLabel($dbopt['keywords'], 'thread');
                    }
                    $Labelogs = &ListLabelog($keywordLs, $search_lg_conditions);
                    if (!empty($Labelogs)) {
                        //必须把手动添加的关联项目加入排除:
                        if ($must_includes > 0)
                            $ExcludeDistRows_1 = array_merge($ExcludeDistRows, $must_include_links);
                        else
                            $ExcludeDistRows_1 = $ExcludeDistRows;
                        $relatedArticles = &SelectiveLabelogs($Labelogs, $keywordLs,null, $ExcludeDistRows_1, 15 - $must_includes);
                        unset($ExcludeDistRows_1);
                        if (!empty($relatedArticles)) {
                            //此步与上步的排除不同:
                            $related_url_fmt = &GenerateRelatedLinks($relatedArticles, 10 - $must_includes, $ExcludeDistRows);
                            if (!empty($related_url_fmt)) {
                                if ($relatedlinks === null) $relatedlinks = '';
                                $relatedlinks .= implode(PHP_EOL, $related_url_fmt);
                                $updcols['relatedlinks'] = &$relatedlinks;
                            }
                        }
                    }
                }
                unset($relatedlinkrules, $must_include_links, $ExcludeDistRows, $must_includes, $search_lg_conditions, $Labelogs);
            }
        }
        elseif ($relatedfids !== NULL && !empty($dbopt) && ($dbopt['relatedfids'] != $relatedfids)) {
            //只改变了relatedfids的情况,取消关联与重启关联:
            if ($relatedfids == '-1') {
                $relatedlinks_txt = ($relatedlinks === NULL ? $dbopt['relatedlinks'] : $relatedlinks);
                if (!empty($relatedlinks_txt)) {
                    $relatedlinkrules =  &ParseRelatedLinkExclude($relatedlinks_txt);
                    if (!empty($relatedlinkrules)) {
                        $relatedlinks = '';
                        foreach ($relatedlinkrules as &$relatedlinkrule) {
                            if (isset($relatedlinkrule['mark']) && !empty($relatedlinkrule['mark'])) {
                                $relatedlinks .= $relatedlinkrule['RawLine'] . PHP_EOL;
                            }
                        }
                        $updcols['relatedlinks'] = &$relatedlinks;
                    }
                }
            } else {
                $relatedlinkrules = $ExcludeDistRows = null;
                $must_include_links = array();
                $must_includes = 0;
                $ExcludeDistRows = array(array('table' => 'thread', 'id' => $tid));//先排除自身
                $relatedlinks_txt = $dbopt['relatedlinks'];
                if (!empty($relatedlinks_txt)) {
                    $relatedlinkrules =  &ParseRelatedLinkExclude($relatedlinks_txt);
                    $edrs = array();
                    if (!empty($relatedlinkrules)) {
                        $relatedlinks = '';
                        foreach ($relatedlinkrules as &$relatedlinkrule) {
                            if (isset($relatedlinkrule['mark']) && !empty($relatedlinkrule['mark'])) {
                                if ($relatedlinkrule['mark'] == '!' || $relatedlinkrule['mark'] == '-')
                                    $edrs[] = &$relatedlinkrule;
                                elseif ($relatedlinkrule['mark'] == '+' || $relatedlinkrule['mark'] == '*') {
                                    $must_includes++;
                                    $must_include_links[] = &$relatedlinkrule;
                                }
                                $relatedlinks .= $relatedlinkrule['RawLine'] . PHP_EOL;
                            }
                        }
                    }
                    if (!empty($edrs)) $ExcludeDistRows = array_merge($ExcludeDistRows, $edrs);
                }
                if ($must_includes < 10) {
                    $search_lg_conditions = array('disabled' => 0, 'fid' => $relatedfids);
                    $keywordLs = StrToLabel($dbopt['keywords'], 'thread');
                    $Labelogs = &ListLabelog($keywordLs, $search_lg_conditions);
                    if (!empty($Labelogs)) {
                        //必须把手动添加的关联项目加入排除:
                        if ($must_includes > 0)
                            $ExcludeDistRows_1 = array_merge($ExcludeDistRows, $must_include_links);
                        else
                            $ExcludeDistRows_1 = $ExcludeDistRows;
                        $relatedArticles = &SelectiveLabelogs($Labelogs, $keywordLs,null, $ExcludeDistRows_1, 15 - $must_includes);
                        unset($ExcludeDistRows_1);
                        if (!empty($relatedArticles)) {
                            //此步与上步的排除不同:
                            $related_url_fmt = &GenerateRelatedLinks($relatedArticles, 10 - $must_includes, $ExcludeDistRows);
                            if (!empty($related_url_fmt)) {
                                $relatedlinks .= implode(PHP_EOL, $related_url_fmt);
                                $updcols['relatedlinks'] = &$relatedlinks;
                            }
                        }
                    }
                }
                unset($relatedlinkrules, $must_include_links, $ExcludeDistRows, $must_includes, $search_lg_conditions, $Labelogs);
            }
        }

        if (!empty($dbopt)) {
            $updRLRet = null;
            $r = db_update($theadext_table, $condext, $updcols);
            if ($r > 0 && $keywords !== null) {
                $Label_extended_fields['dist'] = 'thread';
                $Label_extended_fields['distid'] = $tid;
                $updRLRet = UpdateRelatedLink($dbopt['keywords'], $keywordLs, $Label_extended_fields, $to_chg_kw_fid);
                if (!empty($updRLRet)) {
                    $to_chg_kw_fid = false;
                }
            }
        } else {
            $r = db_insert($theadext_table, array_merge($updcols, $condext));
            if ($r > 0 && !empty($keywords)) {
                $updRLRet = AddLabelLog($keywords, $tid, 'thread', $Label_extended_fields);
            }
        }
        unset($dbopt);
    }
    if ($to_chg_kw_fid) {
        //更新标签记录的distclass
        if (!isset($labellogTB)) $labellogTB = $ghx_cache->get_share_var(VAR_LABELOG_TB);
        $logtables = $ghx_cache->get_share_var(VAR_LIST_DB_TABLES, false, '#^' . preg_quote($db->tablepre, '#') . '(' . preg_quote($labellogTB, '#') . '\d+)$#i');
        if (!empty($logtables)) {
            foreach ($logtables as $tb) {
                $updlbfidr = db_update($tb, array('dist' => 'thread', 'distid' => $tid), array('distclass' => $newfid));
            }
        }
        $to_chg_kw_fid = false;
    }
    //$logstr = print_r(get_defined_vars(), true);
    //write_file('tmp/log.txt', $logstr);

}